package com.hyk.geetest;


import com.hyk.model.LoginForm;
import com.hyk.utils.IpUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.xml.bind.ValidationException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(GeetestProperties.class)
public class GeetestAutoConfiguration {

    private GeetestProperties geetestProperties;

    public GeetestAutoConfiguration(GeetestProperties geetestProperties){
        this.geetestProperties = geetestProperties;
    }

    @Bean
    public GeetestLib setGeetest(){
        return new GeetestLib(geetestProperties.getId(),geetestProperties.getKey());
    }

    public static void checkGeetest(LoginForm loginForm, RedisTemplate<String,Object> redisTemplate, GeetestLib geetestLib) throws ValidationException {
        String challenge = loginForm.getGeetest_challenge();
        String validate = loginForm.getGeetest_validate();
        String seccode = loginForm.getGeetest_seccode();

        Integer status = 0;
        String userId = "";
        try {
            String statusStr = (String) redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY);

            String userIdStr = (String) redisTemplate.opsForValue().get("userId");
            status = Integer.parseInt(statusStr);
            // session必须取出值，若取不出值，直接当做异常退出
            userId = userIdStr;
        } catch (Exception e) {
            throw new ValidationException("极验数据错误");
        }
        GeetestLibResult result = null;
        if (status == 1) {
            /*
            自定义参数,可选择添加
                user_id 客户端用户的唯一标识，确定用户的唯一性；作用于提供进阶数据分析服务，可在register和validate接口传入，不传入也不影响验证服务的使用；若担心用户信息风险，可作预处理(如哈希处理)再提供到极验
                client_type 客户端类型，web：电脑上的浏览器；h5：手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生sdk植入app应用的方式；unknown：未知
                ip_address 客户端请求sdk服务器的ip地址
            */
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            paramMap.put("ip_address", IpUtils.getIpAddr(requestAttributes.getRequest()));
            result = geetestLib.successValidate(challenge, validate, seccode, paramMap);
        } else {
            result = geetestLib.failValidate(challenge, validate, seccode);
        }
        // 注意，不要更改返回的结构和值类型
        if (result.getStatus() != 1) {
            throw new ValidationException("极验数据错误");
        }
    }
}
